<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :showBack="true">
    <template #footer>
      <a-space>
        <a-button @click="router.back()"> 取消 </a-button>
        <a-button type="primary" @click="add"> 提交 </a-button>
      </a-space>
    </template>
    <div class="main">
      <!-- <div class="title">
        <div class="icon"></div>
        <p>基础信息</p>
      </div> -->
      <TitleBox title="基本信息"></TitleBox>
      <div class="form">
        <a-form ref="formRef" :model="form" auto-label-width style="width: 70%" :rules="rules">
          <a-row :gutter="24" justify="space-between">
            <a-col :span="11">
              <a-form-item show-colon label="生产订单编号" label-col-flex="100px" required>
                <a-input disabled placeholder="自动生成生产订单编号" />
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <a-form-item show-colon field="type" label="订单类型" required>
                <a-select :disabled="route.query.id !== undefined" v-model="form.type" placeholder="请选择">
                  <a-option :value="1">面向库存订单</a-option>
                  <a-option :value="2">面向销售订单</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" justify="space-between" v-if="form.type === 2">
            <a-col :span="11">
              <a-form-item show-colon label="关联销售订单号">
                <a-input readonly v-model="form.saleOrderNumber" placeholder="请选择关联销售订单" allow-clear @clear='saleOrderClear'>
                  <template #append>
                    <a-tooltip content="点击选择关联销售订单" mini>
                      <a-button type="dashed" @click="marketModalVisible = true" size="mini">
                        <template #icon>
                          <icon-select-all />
                        </template>
                      </a-button>
                    </a-tooltip>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <!-- {{form.saleOrderids}}
              {{ materialData.data.length}} -->
              <!-- <a-form-item show-colon field="customName" label="客户名称">
                <a-select
                  v-model="form.customId"
                  placeholder="请选择"
                  allow-search
                >
                  <a-option
                    v-for="item in clientList.data"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-option
                  >
                </a-select>
              </a-form-item> -->
            </a-col>
          </a-row>
          <a-row :gutter="24" justify="space-between">
            <a-col :span="11">
              <a-form-item show-colon label="部门名称">
                <!-- <a-input
                v-model="form.departmentName"
                placeholder="请选择部门名称"
              /> -->
                <sectionSelect placeholder="请选择部门名称" :isSearch="true" @selectSection="changeSectionFn" />
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <a-form-item show-colon label="计划人">
                <a-input placeholder="系统自动读取当前操作人" disabled />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" justify="space-between">
            <a-col :span="11">
              <a-form-item show-colon label="创建时间">
                <a-input placeholder="获取电脑当前时间" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <a-form-item show-colon label="创建人">
                <a-input placeholder="系统自动读取当前操作人" disabled />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item field="remark" show-colon label="备 注">
                <a-textarea auto-size style="min-height: 100px" v-model="form.remark" placeholder="请输入" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- <div
        class="title"
        style="padding-bottom: 10px; border-bottom: 1px solid #e4e4e4"
      >
        <div class="icon"></div>
        <p>物料明细</p>
      </div> -->
      <TitleBox title="物料明细"></TitleBox>
      <a-space v-if="form.type === 1" style="padding-left: 20px; margin-bottom: 20px">
        <a-button @click="materielModalVisible = true" type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>新增</template>
        </a-button>
        <a-button @click="delMaterial">
          <template #icon>
            <icon-delete />
          </template>
          <template #default>删除</template>
        </a-button>
      </a-space>
      <!-- 明细表单 -->
      <TableTurn :table-data="getData" :isShowPagination="false" ref="tableRef" :args="{
          rowSelection: {
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false,
          },
        }">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>

        <a-table-column :width="150" align="center" title="物料编码" data-index="number">
        </a-table-column>
        <a-table-column :width="150" align="center" title="物料名称" data-index="name">
        </a-table-column>
        <a-table-column :width="150" align="center" title="规格型号" data-index="spec">
        </a-table-column>
        <a-table-column :width="150" align="center" title="基本单位" data-index="basicName">
        </a-table-column>
        <a-table-column v-if="form.type === 2" :width="150" align="center" title="需求数量" data-index="amount">
        </a-table-column>
        <a-table-column v-if="form.type === 2" :width="150" align="center" title="已转生产数量" data-index="scheduledProduceOrderNumber">
        </a-table-column>
        <a-table-column :width="150" align="center" title="计划生产数量" data-index="repairerName">
          <template #title>
            <div class="title_before">计划生产数量</div>
          </template>
          <template #cell="{ record }">
            <a-input-number :min="1" v-if="form.type === 1" v-model="record.planProduceNumber">
            </a-input-number>
            <a-input-number :min="1" :max="record.amount - record.scheduledProduceOrderNumber" v-else v-model="record.planProduceNumber">
            </a-input-number>
          </template>
        </a-table-column>
        <a-table-column :width="150" align="center" title="紧急等级" data-index="emergencyLevel">
          <template #cell="{ record }">
            <a-select placeholder="请选择" v-model:model-value="record.emergencyLevel">
              <a-option v-for="value in emergencyLevel" :value="value.id" :key="value.id">{{ value.value }}</a-option>
            </a-select>
          </template>
        </a-table-column>
        <a-table-column :width="150" align="center" title="工艺路线" data-index="repairerName">
          <template #cell="{ record }">
            <p>
              {{
                processRoute.data.filter(
                  (ele: any) => ele.productId === record.id
                )[0]?.routerName
                  ? processRoute.data.filter(
                      (ele: any) => ele.productId === record.id
                    )[0]?.routerName
                  : '暂无'
              }}</p>
          </template>
        </a-table-column>
        <a-table-column :width="150" align="center" title="关联产品BOM" data-index="repairerName">
          <template #cell="{ record }">
            <p>
              {{
                bomList.data.filter(
                  (ele: any) => ele.productId === record.id
                )[0]?.bomCode
                  ? bomList.data.filter(
                      (ele: any) => ele.productId === record.id
                    )[0]?.bomCode
                  : '暂无'
              }}
            </p>
          </template>
        </a-table-column>
        <a-table-column :width="160" align="center" title="计划开始时间" data-index="repairerName">
          <template #cell="{ record }">
            <a-date-picker v-model="record.planBeginAt" />
          </template>
        </a-table-column>
        <a-table-column :width="160" align="center" title="计划结束时间" data-index="repairerName">
          <template #cell="{ record }">
            <a-date-picker planEndAt v-model="record.planEndAt" />
          </template>
        </a-table-column>
      </TableTurn>
    </div>
  </pageHeader>

  <materielModal title="物料产品选择" v-model:visible="materielModalVisible" @changeVisible="changeVisible" @searcchMaterialData="updateMaterialData" />
  <marketModal title="关联销售订单选择" :visible="marketModalVisible" :orderList='form.saleOrderids' @changeMarketVisible="changeMarketVisible" @updateMarketData="updateMarketData"></marketModal>
</template>

<script lang="ts" setup>
import { GetClientList } from '@/api/order-management/client-management/client-list';
import { reactive, ref, onBeforeUnmount } from 'vue';
import { PostProduceOrders } from '@/api/produce-management/produce-list/index';
import type { ProduceOrder } from '@/api/produce-management/produce-list/type';
import sectionSelect from '@/components/sectionSelect/index.vue';
import materielModal from '@/components/materielModal/index.vue';
import marketModal from '@/components/marketModal/index.vue';
import pageHeader from '@/components/page-header/index.vue';
import { useRouter, useRoute } from 'vue-router';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import { localNewGetUserInfo } from '@/utils/localStorage/account';
import { GetOrderDetail } from '@/api/order-management/client-order/index';
import {
  GetProductBomPage,
  GetProductProcessRoutePage,
} from '@/api/FactoryModeling';
import { useOrderStore } from '@/store';

const OrderStore = useOrderStore();
const emergencyLevel = [
  { id: 1, value: '一般' },
  { id: 2, value: '紧急' },
  { id: 3, value: '加急' },
  { id: 4, value: '特急' },
];

const title: string = '新建生产订单';
const breadCrumb: string[] = ['生产管理', '生产订单列表', '新建生产订单'];
const router = useRouter();
const route = useRoute();
const form = reactive<ProduceOrder>({});
// const marketId = ref(Number(route.query.id));
const materielModalVisible = ref(false);
const marketModalVisible = ref(false);
const materialData = reactive({ data: [] }); //物料产品选择
const bomList: any = reactive({ data: [] });
const processRoute: any = reactive({ data: [] });
const clientList: any = reactive({ data: [] });
const formRef = ref();
let tableRef = ref();
const rules = {
  type: [
    {
      required: true,
      message: '请选择订单类型',
    },
  ],
};

const getData = async () => {
  form.saleOrderids = form.saleOrderids ?? [];
  let res: any;
  if (OrderStore.product) {
    form.type = 2;
    form.saleOrderNumber = OrderStore.product.saleOrderNumber.join(',');
    form.SaleOrderIds = OrderStore.product.SaleOrderIds;

    // console.log(11111, OrderStore.product);
    materialData.data = OrderStore.product.product;
    OrderStore.product.product.forEach((ele: any) => {
      ele.id = ele.managementId;
    });
    console.log(form, materialData.data);
    // localStorage.setItem('product', JSON.stringify(OrderStore.product));
  }
  // if (marketId.value) {
  //   res = await GetOrderDetail({ id: marketId.value });
  //   const {
  //     clientCompanyName: customName,
  //     clientCompanyId: customId,
  //     number: saleOrderNumber,
  //     id: saleOrderId,
  //   } = res;
  //   form.type = 2;
  //   form.customId = customId;
  //   form.saleOrderNumber = saleOrderNumber;
  //   form.customName = customName;
  //   form.saleOrderId = saleOrderId;
  //   console.log(222, form);
  //   if (OrderStore.product) {
  //     console.log(11111, OrderStore.product);
  //     materialData.data = OrderStore.product;
  //     OrderStore.product.forEach((ele: any) => {
  //       ele.id = ele.managementId;
  //     });
  //     localStorage.setItem('product', JSON.stringify(OrderStore.product));
  //   } else {
  //     const product = localStorage.getItem('product');
  //     materialData.data = product
  //       ? JSON.parse(product)
  //       : Message.error('没有物料产品，请重新操作');
  //   }
  // }

  return Promise.resolve(materialData.data);
};

const init = async () => {
  try {
    const res = await GetProductBomPage({
      page: 1,
      size: -1,
      historyState: 1,
    });
    // const res2 = await GetClientList({ page: 1, size: -1 });
    const res1 = await GetProductProcessRoutePage({
      page: 1,
      size: -1,
      history: 1,
    });
    bomList.data = res.content;
    processRoute.data = res1.content;
    // clientList.data = res2.content;
  } catch (error: any) {
    console.log(error);
    Message.error(error);
  }
};
init();
// 部门名称选择
const changeSectionFn = (e: number) => {
  form.departmentId = e;
};
const changeVisible = (e: boolean) => {
  materielModalVisible.value = e;
};
const changeMarketVisible = (e: boolean) => {
  marketModalVisible.value = e;
};

const updateMaterialData = (data: any) => {
  materialData.data = cloneDeep(data);
  tableRef.value.loadData();
};
// 关联销售订单号重置
const saleOrderClear = (data: any) => {
  form.saleOrderids = [];
  materialData.data = [];
};
// 关联销售订单号选择
const updateMarketData = async (data: any) => {
  if (data && Array.isArray(data) && data.length !== 0) {
    form.saleOrderNumber = data
      .map((ele) => {
        return ele.number;
      })
      .join(',');
    form.saleOrderids = data.map((ele) => {
      return ele.id;
    });
    // form.saleOrderids = [];
    // data.forEach((ele) => {
    //   form.saleOrderids.push(ele.id);
    // });
    // 清空materialData查询赋值
    materialData.data = [];
    data.forEach((item) => {
      // 循环判断item中是否有product属性
      if (item.product) {
        // 然后在tem.product上的没每一个元素进行操作
        item.product.forEach((ele) => {
          // 查询materialData.data数组中是否存在ele.number相同的元素 通过findIndex方法查找
          const index = materialData.data.findIndex(
            (i) => i.number === ele.number
          );
          // 如果找不到就等于-1就将ele的内容添加到materialData.data
          if (index === -1) materialData.data.push({ ...ele });
          else materialData.data[index].amount += ele.amount;
        });
      }
    });
    console.log(form.saleOrderids, materialData.data.length);
    // console.log(data, form.saleOrderids, materialData.data.length);
    tableRef.value.loadData();
    // const {
    //   id,
    //   clientCompanyName: customName,
    //   clientCompanyId: customId,
    //   number: saleOrderNumber,
    // } = data[0];
    // form.customId = customId;
    // form.saleOrderNumber = saleOrderNumber;
    // form.customName = customName;
    // form.saleOrderId = id;
    // const res = await GetOrderDetail({ id });
    // res.orderProduct.forEach((ele: any) => {
    //   ele.id = ele.managementId;
    // });
    // materialData.data = res.orderProduct;
    // tableRef.value.loadData();
  }
};
const delMaterial = () => {
  const ids: number[] = [];
  tableRef.value.selectedList.forEach((ele: any) => {
    ids.push(ele.id);
  });
  materialData.data = materialData.data.filter(
    (ele: any) => ids.indexOf(ele.id) === -1
  );
  tableRef.value.loadData();
  tableRef.value.selectedKeys.length = 0;
};
// 添加
const add = async () => {
  try {
    // 非空校验
    if (await formRef.value.validate()) {
      return;
    }
    if (materialData.data?.length === 0) {
      return Message.error('请选择物料产品');
    }
    const list: any = [];
    materialData.data.forEach((ele: any) => {
      const { emergencyLevel, planProduceNumber, planBeginAt, planEndAt } = ele;
      if (!planProduceNumber) {
        throw new Error('计划生产数量为空');
      }
      list.push({
        ...form,
        materialId: ele.id,
        plannerId: localNewGetUserInfo().id,
        emergencyLevel,
        planProduceNumber,
        planBeginAt: +new Date(planBeginAt),
        planEndAt: +new Date(planEndAt),
      });
    });
    console.log(888, list);
    await PostProduceOrders({ produceOrders: list });
    router.replace({ name: 'ProductionOrder' });
  } catch (error: any) {
    Message.error(`${error}`);
  }
};
onBeforeUnmount(() => {
  localStorage.removeItem('product');
});
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  padding: 10px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .icon {
      background-color: #3d7eff;
      width: 5px;
      height: 20px;
      border-radius: 5px;
      margin-right: 10px;
    }
    p {
      font-size: 16px;
      padding: 0;
      margin: 0;
    }
  }
  .form {
    width: 100%;
    display: flex;
    justify-content: center;
  }
}
.foot {
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px solid #e4e4e4;
  display: flex;
  justify-content: end;
}
.title_before {
  position: relative;
}
.title_before::before {
  content: '*';
  color: red;
  font-size: 16px;
}
</style>
